package zyh.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
//@WebListener
public class GetConnListener implements ServletContextListener{
    public void contextInitialized(ServletContextEvent sce) {
        try {
            ServletContext application=sce.getServletContext();
            String driver=application.getInitParameter("driver");
            String url=application.getInitParameter("url");
            String user=application.getInitParameter("user");
            String pass=application.getInitParameter("pass");
            Class.forName(driver);
            Connection conn= DriverManager.getConnection(url ,user,pass);
            application.setAttribute("conn",conn);
        }
        catch (Exception ex)
        {
            System.out.println("Listener 中获取数据库链接出现异常"+ex.getMessage());
        }
    }

    public void contextDestroyed(ServletContextEvent sce) {
        ServletContext application=sce.getServletContext();
        Connection conn=(Connection)application.getAttribute("conn");
        if(conn !=null)
        {
            try
            {
                conn.close();
            }
            catch (SQLException ex)
            {
                ex.printStackTrace();
            }
        }
    }
}
